package com.qdu.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import com.qdu.util.DateUtil;

@Controller
@RequestMapping("/files")
public class FileController2 {

	@RequestMapping("/upload2") 
	@ResponseBody //处理ajax请求的方法添加@ResponseBody注解
	public String upload(MultipartFile pfile) throws IllegalStateException, IOException {

		System.out.println("......................................");
		
		System.out.println("文件原名称：" + pfile.getOriginalFilename());
		
		String oldName=pfile.getOriginalFilename();
		String newName=UUID.randomUUID().toString().replace("-","")
				       +oldName.substring(oldName.lastIndexOf("."));
		
		System.out.println("文件新名称："+newName); 
		
		String realPath=ResourceUtils.getURL("classpath:static/upload").getPath();
		System.out.println("/static/upload的真实路径："+realPath);
		
		String today=DateUtil.getToday();
		File folder=new File(realPath+"/"+today);
		if(!folder.exists()) //如果文件夹不存在，则创建文件夹，如果存在，不重复创建
			folder.mkdirs(); //创建文件夹
		
		pfile.transferTo(new File(folder,newName));
		
		//返回上传的图片的路径，用于在页面上显示图片
		return today+"/"+newName;
	}
}
